/*
 * Copyright 2008-2023 dexian.vip. All rights reserved.
 * Support: http://www.dexian.vip
 * License: http://www.dexian.vip/license
 */

package vip.dexian.admin.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import vip.dexian.admin.service.CaptchaService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.OutputStream;

/**
 * 验证码
 *
 * @author 挺好的 2023年06月05日 14:43
 */
@Service ("captchaServiceImpl")
@Slf4j
public class CaptchaServiceImpl implements CaptchaService {

    /**
     * 创建验证码
     *
     * @param request
     *         {@link HttpServletRequest }
     * @param response
     *         {@link HttpServletResponse}
     */
    @Override
    @Transactional (propagation = Propagation.SUPPORTS, readOnly = true)
    public void create (HttpServletRequest request, HttpServletResponse response) {
        try (OutputStream out = response.getOutputStream()) {
            CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 20);

            response.setContentType(MediaType.IMAGE_JPEG_VALUE);

            String code = captcha.getCode();

            HttpSession session = request.getSession();

            session.setAttribute(CAPTCHA_ATTRIBUTE_NAME, code);

            captcha.write(out);

        } catch (Exception e) {
            log.error("生成验证码失败", e);
        }
    }

    /**
     * 是否有效
     *
     * @param request
     *         {@link HttpServletRequest }
     * @param captcha
     *         验证码
     *
     * @return captcha is empty || 不正确，返回false
     */
    @Override
    @Transactional (propagation = Propagation.SUPPORTS, readOnly = true)
    public boolean isValid (HttpServletRequest request, String captcha) {

        if (StringUtils.isEmpty(captcha)) {
            return false;
        }
        HttpSession session = request.getSession();

        String sessionCaptcha = (String) session.getAttribute(CAPTCHA_ATTRIBUTE_NAME);

        session.removeAttribute(CAPTCHA_ATTRIBUTE_NAME);

        return StringUtils.equals(captcha, sessionCaptcha);
    }
}
